package attribute

import (
	"context"
	"strings"

	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/product/rpc/productclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAttributeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateAttributeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAttributeLogic {
	return &UpdateAttributeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateAttributeLogic) UpdateAttribute(req *types.UpdateAttributeReq) (resp *types.BaseMsgResp, err error) {
	if len(req.Ids) > 0 {
		res, err := l.svcCtx.ProductRpc.UpdateAttribute(l.ctx, &productclient.AttributeInfo{
			Status: req.Status,
			Ids:    req.Ids,
		})
		if err != nil {
			return nil, err
		}

		return &types.BaseMsgResp{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
		}, nil
	}

	if req.Id == nil || *req.Id == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.Name != nil && len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "attribute.nameRequired"))
	}

	adminId := jwt.GetBackendUserId(l.ctx)

	res, err := l.svcCtx.ProductRpc.UpdateAttribute(l.ctx, &productclient.AttributeInfo{
		Id:          req.Id,
		TermId:      req.TermId,
		Taxonomy:    req.Taxonomy,
		IsVariation: req.IsVariation,
		Name:        req.Name,
		Slug:        req.Slug,
		HasMedia:    req.HasImage,
		Sort:        req.Sort,
		Status:      req.Status,
		UpdatedBy:   pointy.GetPointer(adminId),
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
